import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import SockJS from '../utils/sockjs'
import '../utils/stomp'
import { Notification } from 'element-ui'
import router from '@/router'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    settings,
    user
  },
  getters,
  state: {
    stomp: null,
    isConnected: false
  },
    actions: {
    connect(context) {
      // 连接Stomp站点
      // eslint-disable-next-line no-undef
      context.state.stomp = Stomp.over(new SockJS('/ws-api/ws'))
      context.state.stomp.connect({}, () => {
        context.state.isConnected = true
        console.log('WebSocket连接成功')
        /**
         * 订阅系统广播通知消息
         */
        context.state.stomp.subscribe('/topic/stream',msg =>{
          console.log('收到WebSocket消息:',msg)
          
          let title = '系统通知'
          let message = msg.body
          let type = 'info'
          
          // 尝试解析JSON格式的消息
          try {
            const data = JSON.parse(msg.body)
            if (data.title) title = data.title
            if (data.content) message = data.content
            if (data.type) type = data.type
          } catch (e) {
            // 如果不是JSON格式，使用原始消息体
            message = msg.body
          }
          
          // 处理接收到的消息
          // 弹框点击跳转
          Notification({
            title: title,
            message: message,
            type: type,
            duration: 10000,
            onClick: () => {
              // 跳转到指定页面
              router.push('/message/messageList')
            }
          })
        })
      },error => {
        context.state.isConnected = false
        console.log('WebSocket连接失败:',error)
      })
    },
    disconnect(context){
      if (context.state.stomp!=null) {
        context.state.stomp.disconnect()
        context.state.isConnected = false
        console.log('WebSocket连接已关闭')
      }
    }
  }
})

export default store
